/**
 *  *2010-4-22 上午10:18:02  add 
 */
package com.base.myproject.client.busi.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.ColumnInfo;
import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.busi.ccode.NewCCode;
import com.base.myproject.client.busi.print.PrintDialogX;
import com.base.myproject.client.busi.system.BcodeChecker;
import com.base.myproject.client.busi.system.BcodeSync;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.system.Env;
import com.base.myproject.client.system.SystemMessage;
import com.base.myproject.client.tools.CommandSyncAssociator;
import com.base.myproject.client.tools.CommandSyncContainer;
import com.base.myproject.client.tools.CommandSyncHasCcode;
import com.base.myproject.client.tools.CommandSyncReturnObject;
import com.base.myproject.client.tools.CommandSyncsql;
import com.base.myproject.client.tools.Debug;
import com.base.myproject.client.ui.BaseBusiLeftPanel;
import com.base.myproject.client.ui.BaseFormPanel;
import com.base.myproject.client.ui.BaseGrid;
import com.base.myproject.client.ui.celleditor.BaseGridEditor;
import com.base.myproject.client.ui.celleditor.CellEditorFactory;
import com.base.myproject.client.ui.celleditor.GridEditor;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.Style.VerticalAlignment;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.FieldEvent;
import com.extjs.gxt.ui.client.event.GridEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.store.Store;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.FieldSet;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.AggregationRowConfig;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnData;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridCellRenderer;
import com.extjs.gxt.ui.client.widget.grid.SummaryType;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.layout.TableData;
import com.extjs.gxt.ui.client.widget.layout.TableLayout;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.xml.client.Element;

/**
 * @author Administrator
 *2010-4-22
 * javazgw@gmail.com
 */
public class ServiceListing2 extends ServiceListing{

	
	/**
	 * 头部界面，主界面
	 */
	protected ContentPanel createService() {
		 service_panel = new ContentPanel();
		 
		 bfp = new BaseFormPanel(store);
		
		TableLayout tl = new TableLayout(4);
		tl.setWidth("600");
		
		bfp.setLayout(tl);
		bfp.setHeaderVisible(false);
		 


		 peoplenum = new NumberField();
		peoplenum.setName("peoplenum");
		peoplenum.setAllowBlank(false);
		peoplenum.setFieldLabel("服务人数");

		
		 createdate = new DateField();
		createdate.setName("createdate");
		createdate.setAllowBlank(false);
		createdate.getPropertyEditor().setFormat(DateTimeFormat.getFormat("yyyy-M-d H:mm:ss"));  
		createdate.setFieldLabel("建立日期");
		createdate.setVisible(false);
		
		
		servicestartdate = new DateField();
		servicestartdate.setName("servicestartdate");
		servicestartdate.setAllowBlank(false);
		servicestartdate.getPropertyEditor().setFormat(DateTimeFormat.getFormat("yyyy-M-d H:mm:ss"));  
		servicestartdate.setFieldLabel("服务开始时间");
		
		serviceenddate = new DateField();
		serviceenddate.setVisible(false);
		serviceenddate.setName("serviceenddate");
	//	serviceenddate.setPropertyEditor(propertyEditor)
		//n.setPropertyEditorType(Integer.class);
		serviceenddate.setFormatValue(true);
		//serviceenddate.setAllowBlank(false);
		serviceenddate.getPropertyEditor().setFormat(DateTimeFormat.getFormat("yyyy-M-d H:mm:ss"));  
		serviceenddate.setFieldLabel("服务结束时间");
		
		 roomno = new TextField<String>();
		roomno.setName("roomno");
	//	roomno.setAllowBlank(false);
		roomno.setFieldLabel("房间号");

		Accounts = new NumberField();
		Accounts.setName("Accounts");
		Accounts.setAllowBlank(false);
//		Accounts.getPropertyEditor().set
//		Accounts.setPropertyEditor(propertyEditor)
//		setPropertyEditorType(Integer.class);
	//	Accounts.getPropertyEditor().
		Accounts.setFieldLabel("应收金额");
		Accounts.setAllowBlank(true);
		 Paid = new NumberField();
		Paid.setName("Paid");
		Paid.setAllowBlank(false);
		Paid.setFieldLabel("实收金额");

		
		TextField<String> icode = new TextField<String>();
		icode.setName("icode");
		icode.setAllowBlank(false);
		icode.setEnabled(false);
		icode.setFieldLabel("编号");


		
		TableData bfp_td = new TableData();
		bfp_td.setColspan(1);
		bfp_td.setRowspan(1);
		// 对齐方式
		bfp_td.setHorizontalAlign(HorizontalAlignment.LEFT);
		bfp_td.setVerticalAlign(VerticalAlignment.TOP);
		bfp_td.setPadding(5);
		
		

		
		
	
	
		
		
//		bfp.add(new Label("客户名:"),bfp_td);
//		bfp.add(ccode,bfp_td);
		bfp.add(new Label("人数:"),bfp_td);
		bfp.add(peoplenum,bfp_td);
		bfp.add(new Label("房间号:"),bfp_td);
		bfp.add(roomno,bfp_td);
//		bfp.add(new Label("开始服务时间:"),bfp_td);
//		bfp.add(servicestartdate,bfp_td);
		//bfp.add(new Label("结束服务时间:"),bfp_td);
	
		bfp.add(new Label("应收款:"),bfp_td);
		bfp.add(Accounts,bfp_td);
		bfp.add(new Label("实收款:"),bfp_td);
		bfp.add(Paid,bfp_td);
	
		bfp.add(serviceenddate,bfp_td);
		bfp.add(createdate,bfp_td);
	
		bfp.inited();
		/*
		 * leftpanel.add(codename); rightpanel.add(ccode);
		 * leftpanel.add(codename); rightpanel.add(ccode);
		 */

//		leftpanel.inited();
//		rightpanel.inited();
	
		
		TableData td = new TableData();
		td.setColspan(1);
		td.setRowspan(1);
		// 对齐方式
		td.setHorizontalAlign(HorizontalAlignment.LEFT);
		td.setVerticalAlign(VerticalAlignment.TOP);

		FieldSet fieldSet = new FieldSet();
		//fieldSet.setHeading("");
		
		fieldSet.setLayout(new TableLayout(1));
//		fieldSet.add(leftpanel, td);
//		fieldSet.add(rightpanel, td);
//		
		fieldSet.add(bfp, td);
		
//
	//	fieldSet.add(hpanel, td);

		final BorderLayout layout = new BorderLayout();
		service_panel.setHeaderVisible(false);
		service_panel.setLayout(layout);
		BorderLayoutData centerData = new BorderLayoutData(LayoutRegion.CENTER);
		centerData.setMargins(new Margins(5, 0, 5, 0));
		service_panel.add(fieldSet, centerData);
		// panel.setAutoHeight(true);
		service_panel.setHeight("120");
		service_panel.setWidth("600");
		//service_panel.setAutoWidth(true);
		//panel.setEnabled(false);
		//panel.mask("", "base-x-item-disabled");
		
		return service_panel;

	}
	public ContentPanel CreateCcodeLeftPanel() {
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		ColumnConfig icode = new ColumnConfig("icode", "单号", 40);
		
		//columns.add(icode);
//		columns.add(new ColumnConfig("ccode	", "ccode", 50));
//		columns.add(new ColumnConfig("roomno", "roomno", 50));
		ColumnConfig busistatus = new ColumnConfig("busistatus", "状态", 40);
		
		GridCellRenderer<ModelData>	renderer = new GridCellRenderer<ModelData>() {

		      public String render(ModelData model, String property, ColumnData d, int rowIndex,
		          int colIndex, ListStore<ModelData> store, Grid<ModelData> grid) {

		       if(model.get(property)==null)
		        return "" ;

		       if(model.get(property).equals("524288"))
		           return "" + ("<img src='images/baseimage/money_yen.png' />" );
//		       else if(model.get(property).equals("2"))
//		       	   return "" + ("<img src='../images/baseimage/icon-complete.gif' />" );
		          return "" + ("<img src='images/baseimage/cut.png' />" );
		      // return SystemMessage.getstatus(model.get(property)+"");
		      }
		    };
		    busistatus.setRenderer(renderer) ;
		columns.add(busistatus);
		columns.add(new ColumnConfig("s_cardno", "会员卡", 150));
//		columns.add(new ColumnConfig("s_mobil", "电话", 80));
//		columns.add(new ColumnConfig("createdate", "日期", 100));
/*		ColumnConfig servicestartdate = new ColumnConfig("servicestartdate", "servicestartdate", 50);

		columns.add(servicestartdate);*/
		//ColumnModel cm = new ColumnModel(columns);

		// --set modetype
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");
		type.addField("icode");
		type.addField("busicode");
		type.addField("bcode");
		type.addField("ccode");
		type.addField("busistatus");
		type.addField("vprepare");
		type.addField("predate");
		type.addField("modifydate");
		type.addField("codename");
		type.addField("odate");
		type.addField("mark");

		type.addField("peoplenum");
		type.addField("Accounts");
		type.addField("Paid");
		type.addField("servicestartdate");
		type.addField("serviceenddate");
		type.addField("roomno");
		type.addField("s_cardno");
		//type.addField("check_isas");
		type.addField("createdate");
		
		type.addField("cname");
		type.addField("s_mobil");
		type.addField("lastfiannce");
		
		
		type.getField("Accounts").setType(Double.class);
		type.getField("Paid").setType(Double.class);
		type.getField("peoplenum").setType(Integer.class);
		type.getField("servicestartdate").setType(Date.class);
		type.getField("serviceenddate").setType(Date.class);
		//type.getField("check_isas").setType(Boolean.class);
		type.getField("lastfiannce").setType(Double.class);
		
		StoreInfo info = new StoreInfo();
		info.setTablename("s_service_po");
		info.setKeyname(new String[] { "icode" });
		info.setSql("select * from s_service_po where DATEDIFF(day, getdate(), createdate)=0 and bcode='"+Env.getEnvbcode()+"'");
		// info.setKeyname(new String[] { "codename" });

		BaseBusiLeftPanel<BusiObject> basbusileftpanel = new BaseBusiLeftPanel<BusiObject>(columns,
				type, info)
		{
			protected boolean Select(Store<BusiObject> store,
					BusiObject parent, BusiObject record, String property,
					String filter) {
				for (int i = 0; i < type.getFieldCount(); i++) {
					
					Object name = record.get(type.getField(i).getName());
				//状态用了码名映射，所以要对名字进行搜索
					if(type.getField(i).getName().equals("busistatus"))
					{
						if(name!=null && SystemMessage.getstatus(name+"").indexOf(filter.toLowerCase()) !=-1)
						{
							return true;
						}
						
					}
					
					else if (name!=null&&name.toString().indexOf(filter.toLowerCase()) != -1) {
						return true;
					}
				}
				return false;
			}
			
			public boolean candeleterecord()
			{
				if(this.getStore().getCount()<=0)
				{
					return false;
				}
				if(this.getStore().getValue("busistatus").equals("524288"))
				{
				MessageBox.alert("警告", "不能被删除，因为已经被收银。",	null);
				return false;
				
				}
				return true;
			}
			
			public void doBeforeRowChangeGrid()
			{
				if(store.isIschanged() || s_service_po_g_store.isIschanged() )
				{
					store.trySave();
				}
				
			}
			
			public void setdefault()
			{
				DateTimeFormat activeFormat = DateTimeFormat
				.getFormat("yyyy-M-d H:mm:ss");
				
//				store.addDefault("createdate",activeFormat.format(new Date()));
				store.addDefault("createdate",new Date());
				//store.addDefault("servicestartdate",new Date());
			}
		};
		store = basbusileftpanel.getStore();
		store.addDefault("busistatus","128");
		store.applyFilters("524288");
		basbusileftpanel.getGrid().setAutoExpandColumn("createdate");
		basbusileftpanel.getGrid().setWidth("240");
		basegrid = basbusileftpanel.getGrid();
		setMaincomponent(basegrid);
		return basbusileftpanel.getPanel();
	}
	/**
	 * 服务类型
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected BaseGrid createServiceItem() {
		CheckBoxSelectionModel cbs = new CheckBoxSelectionModel();
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		columns.add(cbs.getColumn());

		
		// ---------------
		List<ColumnConfig> bocodecolumns = new ArrayList<ColumnConfig>();
		ColumnConfig service = new ColumnConfig("service", "服务类型", 120);

		bocodecolumns.add(service);

		ColumnConfig price = new ColumnConfig("price", "单价", 100);
		price.setAlignment(HorizontalAlignment.RIGHT);
		price.setNumberFormat(NumberFormat.getCurrencyFormat());

		bocodecolumns.add(price);
		ColumnConfig priceunit = new ColumnConfig("priceunit", "单位", 50);

		bocodecolumns.add(priceunit);

		ModelType combotype = new ModelType();
		combotype.setRoot("records");
		combotype.setRecordName("record");
		combotype.setTotalName("totle");
		// combotype.addField("code", "service");
		combotype.addField("service");
		combotype.addField("priceunit");
		combotype.addField("price");
	//	combotype.addField("bcode");
		StoreInfo comboinfo = new StoreInfo();
		comboinfo.setTablename("s_service");
		comboinfo.setSql("select service,priceunit,price from s_service where service is not null and priceunit is not null and price>0");
		comboinfo.setForcenolimit("true");
		BaseGridEditor bge = new BaseGridEditor(bocodecolumns, combotype,
				comboinfo, "service");
		

		ColumnConfig serviceitem = new ColumnConfig("serviceitem", "服务类型", 80);
		//TextField<String> serviceitemtext = new TextField<String>();
		GridEditor grideditor = new GridEditor(bge);
		serviceitem.setEditor(grideditor);
		serviceitem.setRenderer(grideditor);
		grideditor.getField().setName("serviceitem");
		grideditor.getField().addListener(Events.Change, this);
		
		ColumnConfig method = new ColumnConfig("method", "指定方式", 80);
		CellEditorFactory  cef = new CellEditorFactory();
		CellEditor ce1  = cef.getMethodCellEditor();
		method.setEditor(ce1);
		
		
		

		ColumnConfig qty = new ColumnConfig("qty", "数量", 50);
		qty.setAlignment(HorizontalAlignment.RIGHT);
		//qty.setNumberFormat(NumberFormat.getFormat("#,##0"));
		NumberField n = new NumberField();
		n.setFormat(NumberFormat.getFormat("#,##0"));
		n.setPropertyEditorType(Integer.class);
		n.setName("qty");
		n.addListener(Events.Change, this);
		qty.setEditor(new CellEditor(n));
		//qty.getEditor().addListener(Events.Complete, this);
		
		ColumnConfig upric = new ColumnConfig("upric", "单价", 80);
		// TextField<String> uprictext = new TextField<String>();
		// upric.setEditor(new CellEditor(uprictext));
		upric.setAlignment(HorizontalAlignment.RIGHT);
		upric.setNumberFormat(NumberFormat.getCurrencyFormat());
		upric.setEditor(new CellEditor(new NumberField()));
		upric.getEditor().getField().setName("upric");
		upric.getEditor().getField().addListener(Events.Change, this);
		//upric.getEditor().addListener(Events.Complete, this);
	
		ColumnConfig qtyunit = new ColumnConfig("qtyunit", "单位", 50);
		TextField<String> qtyunittext = new TextField<String>();
		qtyunit.setEditor(new CellEditor(qtyunittext));
		
		
		ColumnConfig total = new ColumnConfig("total", "小计", 80);
		// TextField<String> uprictext = new TextField<String>();
		// upric.setEditor(new CellEditor(uprictext));
		total.setAlignment(HorizontalAlignment.RIGHT);
		total.setNumberFormat(NumberFormat.getCurrencyFormat());
		//total.setEditor(new CellEditor(new NumberField()));
		
	
		
		
		

			
		
		 //**********************************
			ColumnConfig c9 = new ColumnConfig("bcodeshortcode", "技师编号", 70);
			TextField<String> c9text = new TextField<String>();
			c9.setEditor(new CellEditor(c9text));
			c9text.setName("bcodeshortcode");
			c9text.addListener(Events.Change, this);
			
			c9text.setFireChangeEventOnSetValue(true);
			
			
			//c9.getEditor().getField().addListener(Events.Change, this);
			
			ColumnConfig c10 = new ColumnConfig("bname", "技师名", 80);
			TextField<String> c10text = new TextField<String>();
			c10.setEditor(new CellEditor(c10text));
			c10text.setName("bname");
//		columns.add(bcode);
			columns.add(c9);
			columns.add(c10);
		columns.add(method);
		columns.add(serviceitem);
		
		columns.add(qty);
		columns.add(upric);
		columns.add(qtyunit);
		columns.add(total);
		qtyunit.getEditor().addListener(Events.Complete, this);
		upric.getEditor().addListener(Events.Complete, this);
		
		
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");

		type.addField("idx");
		type.addField("icode");

		type.addField("serviceitem");

		type.addField("qty");

		type.addField("qtyunit");
		type.addField("upric");
		type.addField("bcode");
		type.addField("method");
		type.addField("total");
		type.addField("bcodeshortcode");
		type.addField("bname");
		type.getField("qty").setType(Integer.class);
		type.getField("total").setType(Double.class);
		type.getField("upric").setType(Double.class);
		type.getField("bcode").setType(String.class);
		StoreInfo info = new StoreInfo();

		info.setTablename("s_service_po_g");
		info.setSql("select * from s_service_po_g where upicode='{icode}'");
		info.setParent(store);// 关联主表
		// info.setAutoinccolumn("idx"); // 自增字段，如果子表一定需要
		info.setLinkparentcolumns(new String[] { "icode" }); // 关联主表字段
		info.setLinkparent_chile_columns(new String[] { "upicode" });// 关联主表字段
																		// (子表)

		info.setKeyname(new String[] { "icode" }); // 主键

		s_service_po_g_store = new BaseStore<BusiObject>(type, info);
		s_service_po_g_store.setName("s_service_po_g");
		
	

		ColumnModel cm = new ColumnModel(columns);

		AggregationRowConfig averages = new AggregationRowConfig();
		averages.setHtml("serviceitem", "合计：");

		averages.setSummaryType("total", SummaryType.SUM);
		averages.setSummaryFormat("total", NumberFormat.getCurrencyFormat());
		
		 cm.addAggregationRow(averages);

		bge.setTarget_store(s_service_po_g_store);
		bge.setSourcecol(new ColumnInfo[] { new ColumnInfo("priceunit",ColumnInfo.STRING), new ColumnInfo("price",ColumnInfo.DOUBLE) });
		bge.setTarget_col(new ColumnInfo[] { new ColumnInfo("qtyunit",ColumnInfo.STRING), new ColumnInfo("upric",ColumnInfo.DOUBLE) });
		//		
		 s_service_po_g_grid = new BaseGrid(s_service_po_g_store, cm)
		 {
			 public void deleterecord(){
				 super.deleterecord();
				 trysave();
				 cal();
			 }
		 };
	
		cbs.setSelectionMode(SelectionMode.SINGLE);
		
		s_service_po_g_grid.setSelectionModel(cbs);
//		s_service_po_g_grid.setAutoHeight(true);

		//s_service_po_g_grid.setAutoWidth(true);
		s_service_po_g_grid.setWidth("600");
		s_service_po_g_grid.setHeight(310);
	

		registerStore(s_service_po_g_store);
		// bcgp = new
		// BaseChileGridPanel(type,info,columns,BaseChileGridPanel.QUERY_MODE);
		//s_service_po_g_store.addBaseStoreListener(BaseStoreEvent.EventType.CELL_CHANGED, this);
		s_service_po_g_grid.addListener(Events.AfterEdit, this );
		return s_service_po_g_grid;
	}
	public void Print() { 
		PrintDialogX pdx = new PrintDialogX(busi,"&icode="+store.getValue("icode"));
		pdx.show();
	}
	 int sync = 0;
		/* (non-Javadoc)
		 * @see com.extjs.gxt.ui.client.event.Listener#handleEvent(com.extjs.gxt.ui.client.event.BaseEvent)
		 */
		public void handleEvent(BaseEvent be) {
			
			sync++;
			try {
				if (sync == 1) {

					
					Debug.printf(be.getType(), 4);
					if (be.getType() == Events.Select) {
						if (be.getSource() == startbutton) {
							Date d = new Date();
							/*
							 * DateTimeFormat activeFormat =
							 * DateTimeFormat.getFormat("yyyy-M-d h:mm:ss"); String
							 * formattedValue = activeFormat.format(d);
							 */
							servicestartdate.setFireChangeEventOnSetValue(true);
							servicestartdate.setValue(d);
							// servicestartdate.setRawValue(formattedValue);
						} else if (be.getSource() == endbutton) {
							Date d = new Date();
							/*
							 * DateTimeFormat activeFormat =
							 * DateTimeFormat.getFormat("yyyy-M-d h:mm:ss"); String
							 * formattedValue = activeFormat.format(d);
							 */
							serviceenddate.setFireChangeEventOnSetValue(true);
							serviceenddate.setValue(d);
						} else if (be.getSource() == paidbutton) {
							
							paidX();
				
						}
						else if (be.getSource() == printer) {
							
//							store.setValue("busistatus", "128");
//							store.setValue("busistatus", "524288");
							Object status = store.getValue("busistatus");
							if(status!=null && status.equals("524288"))
							{
							Print() ;
							}
							else
							{
								MessageBox.alert("警告", "必须先进行“收银”才能进行“打印”。\n“收银”按钮在工具栏。", null);
							}
						}
						else if (be.getSource() == addnew) {
							
							basegrid.addnewrecord();
						}
						
						else if (be.getSource() == getassoc_button) {
							if(!(s_cardnothis.getValue()==null || s_cardnothis.getValue().equals("")) )
							{
							final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
							.create(com.base.myproject.client.tools.GreetingService.class);
							greetingService.getAssociator(s_cardnothis.getValue(),4,this);
							}
							else if(!(cname_t.getValue()==null || cname_t.getValue().equals("")) )
							{
							final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
							.create(com.base.myproject.client.tools.GreetingService.class);
							greetingService.getAssociator(cname_t.getValue(),2,this);
							}
							else if(!(s_mobil.getValue()==null || s_mobil.getValue().equals("")) )
							{
							final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
							.create(com.base.myproject.client.tools.GreetingService.class);
							greetingService.getAssociator(s_mobil.getValue(),3,this);
							}
						}
						else if (be.getSource() == associatorbutton) {
							AssociatorPanel associatorpanel = new AssociatorPanel();
							associatorpanel.getDialog().show();
						}
						else if (be.getSource() == changedpo) {
							
							BcodeChecker b = new BcodeChecker(){

								@Override
								public void onFailure(Throwable caught) {
									// TODO Auto-generated method stub
									
								}

								@Override
								public void onSuccess(Boolean result) {
									Debug.printf(result.toString());
									GWT.log("result", null);
									if(result)
									{
										
										store.setValue("busistatus", "128");
										vpanel.unmask();
										
									}
									else
									{
										Info.display("","密码不正确!!");
										
									}
								}
								
							};
					
							b.showDialog();
						
							
						}
						
						else if (be.getSource() == addfinance) {
							//bug
							AddFinace addfinace = new AddFinace()
							{
								public void addfinancesuccess(Element elem ) {
									super.addfinancesuccess(elem);
									if(check_isas.getValue()!=null && check_isas.getValue() && s_cardno.getValue()!=null)
									{
									final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
									.create(com.base.myproject.client.tools.GreetingService.class);
									greetingService.getAssociator(s_cardno.getValue(),4,new AsyncCallback<Associator> (){

										@Override
										public void onFailure(Throwable caught) {
											// TODO Auto-generated method stub
											
										}

										@Override
										public void onSuccess(Associator result) {
										//	if(associator.getS_cardno().equals(result.getS_cardno()))
											GWT.log("---"+s_cardnothis.getValue(), null);
											GWT.log("==="+result.getS_cardno(), null);
											System.out.println("---"+s_cardnothis.getValue());
											System.out.println("==="+result.getS_cardno());
											if(s_cardnothis.getValue().equals(result.getS_cardno()))
											getAssociatorSuccess(result);
										}
										
									});
									}
								}
							};
							addfinace.showDialog();
							
//							new AddFinace().showDialog();
						}
						//交接
						else if (be.getSource() == associate) {
							printer();
						}
						//添加新会员
						else if(be.getSource().equals(newccode))
						{
							 NewCCode newccode = new NewCCode();
							 newccode.show();
						}
						
					} else if (be.getType() == Events.Change) {
						Debug.printf("changed!!", 4);
						// String name = (be.getSource()).getField().getName();
						Debug.printf("changed!!"
								+ ((FieldEvent) be).getField().getName(), 4);
						String name = ((FieldEvent) be).getField().getName();
						if (name.equals("qty")) {
							
						} else if (name.equals("upric")) {
						

						}
						else if (name.equals("bcodeshortcode")) {}
						
						// 录入卡号
						else if (name.equals("s_cardno")) {
							Debug.printf("s_cardno input ", 4);

							be.setCancelled(true);
							final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
							.create(com.base.myproject.client.tools.GreetingService.class);
							greetingService.getAssociator(s_cardnothis.getValue(),4,this);

						} 

						


					}
					else if (be.getType() == Events.KeyUp) {
						Debug.printf("keyup" +be.getClass());
						Debug.printf("keyup" +be.getType());
						if(be instanceof ComponentEvent)
						{
							Debug.printf("keyup" +((ComponentEvent) be).getKeyCode());
							if(((ComponentEvent) be).getKeyCode()==9)
							{
								
							}
						
							else if(be.getSource().equals(s_cardnothis))
						{
							
								ccode.setFireChangeEventOnSetValue(true);
								cname_t.setFireChangeEventOnSetValue(true);
								s_mobil.setFireChangeEventOnSetValue(true);
								//s_cardnothis.setFireChangeEventOnSetValue(true);
								html.setFireChangeEventOnSetValue(true);
								//s_cardnothis.setValue("");
								ccode.setValue("");
								html.setValue(0);
								
								
								cname_t.setValue("");
								s_mobil.setValue("");
								
								//s_cardnothis.setFireChangeEventOnSetValue(false);
								ccode.setFireChangeEventOnSetValue(false);
								cname_t.setFireChangeEventOnSetValue(false);
								s_mobil.setFireChangeEventOnSetValue(false);
								html.setFireChangeEventOnSetValue(false);
						}
						else if(be.getSource().equals(s_mobil))
						{
							s_cardnothis.setValue("");
							cname_t.setValue("");
							html.setValue(0);
						}
						else if(be.getSource().equals(cname_t))
						{
							s_mobil.setValue("");
							s_cardnothis.setValue("");
							html.setValue(0);
						}
						}
					}
					else if (be.getType() == Events.AfterEdit) {
						Debug.printf("ddd");
						final GridEvent<BusiObject> be2 = (GridEvent<BusiObject>)be;
						//((BaseGrid<BusiObject>)be2.getGrid()).setValue(be2.getRowIndex(), "bname", "sss");
						

						
						
						if (be2.getProperty().equals("bcodeshortcode")) {
							final int index = be2.getRowIndex();
							Debug.printf("index = " + index);
							if (index != -1) {

								// Object shortcode = ((FieldEvent)
								// be).getField().getValue();
								Object shortcode = be2.getValue();
								if (shortcode != null) {
									String shortcodestr = shortcode.toString();
									final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
											.create(com.base.myproject.client.tools.GreetingService.class);
								//	greetingService.getbnamebyshortname(shortcodestr, new AsyncCallback<String>() {
									greetingService.getBcode("bcodeshortcode",shortcodestr, new AsyncCallback<BcodeSync>() {
									
										@Override
										public void onFailure(Throwable caught) {

										}

										@Override
										public void onSuccess(BcodeSync result) {
											if (result != null) {
												Debug.printf("index2 = " + result.getBname()+""+result.getBcodeshortcode());
//												s_service_po_g_store.setValue(index,
//														"bcode", result[0]);
//												s_service_po_g_store.setValue(index,
//														"bname", result[1]);
												
										//		((BaseGrid<BusiObject>)be2.getGrid()).setValue(be2.getRowIndex(), "bcode", result[0]);
												((BaseGrid<BusiObject>)be2.getGrid()).setValue(be2.getRowIndex(), "bname", result.getBname());
												
											}
										}

									});
								}
							}
						
					}
						else if (be2.getProperty().equals("qty") || be2.getProperty().equals("upric") ||be2.getProperty().equals("serviceitem")) {

							final int index = be2.getRowIndex();
							if (index != -1) {
								double qty = Double.parseDouble(((BaseGrid<BusiObject>)be2.getGrid()).getValue(index, "qty") == null ? "0"
										: ((BaseGrid<BusiObject>)be2.getGrid()).getValue(index, "qty").toString());
								
								double price = Double
										.parseDouble(((BaseGrid<BusiObject>)be2.getGrid()).getValue(index, "upric") == null ? "0"
												: ((BaseGrid<BusiObject>)be2.getGrid()).getValue(index, "upric").toString());
								// total

								((BaseGrid<BusiObject>)be2.getGrid()).setValue(index, "total", qty
										* price);

								cal();
							}

						
						}
					

						
					}
					
				}
				}
			
				finally {
				sync--;
				Debug.printf("suync="+sync, 4);
			}
			
		}
	/**
	 * 对话框方式
	 */
	public void paidX()
	{

		
		
		//保证  “实收款” 先录入，
			if(Paid.getValue()==null || Paid.getValue().doubleValue()<1)
			{
				
				MessageBox.alert("禁止", "请先录入 “实收款”金额。", null);
				
			}
			else if(!store.getValue("busistatus").equals("128"))
			{
				MessageBox.alert("禁止", "你已经进行过此操作，如果单据录入错误，请先“修改此单据”", null);
			}
			else
			{
			 PaidDialog pd = new PaidDialog(){
				 
				 protected void onOK(){
						
						Date d = new Date();
						serviceenddate
								.setFireChangeEventOnSetValue(true);
						serviceenddate.setValue(d);
						int index = store.getCurcowindex();
						//
						CommandSyncContainer list = new CommandSyncContainer();
						
						//判断采用的付款方式
						//------------------start
						int paymodecount=0;
						//1 ：会员；2：现金;3:消费券；4：刷卡
						int paymode=0;
						if(this.getS_cardno()!=null )
						{
							paymodecount+=1;
							paymode=1;
						}
					if (this.getXianjin().getValue() != null) {
						paymodecount += 1;
						paymode=2;
					}
					if (this.getXiaofeiquan().getValue() != null) {
						paymodecount += 1;
						paymode=3;
					}
					if (this.getShuaka().getValue()) {
						paymodecount += 1;
						paymode=4;
					}
						
						if(paymodecount>=2 || paymodecount==0)
						{
							MessageBox.alert("警告","你必须（只）选择一种收款方式！", null	);
							return;
						}
						//------------------end
						
						if(this.getS_cardno()!=null)
						{
						CommandSyncHasCcode hasccode = new CommandSyncHasCcode();
						hasccode.setContinueorrollback(false);
						hasccode.setS_cardno(this.getS_cardno());
						hasccode.setPassword(this.getPassword());
						list.add(hasccode);
						
						}
						//清空会员卡
						else 
						{
							store.setValue("s_cardno",null);
							store.setValue("ccode",null);
						}
						CommandSyncsql commandsql = new CommandSyncsql();
						commandsql.getV().addAll(store._trySave(store.getCurcowindex()));
						
						
						String icode = store.getValue(index, "icode").toString();
						

						
						list.add(commandsql);
						
						if(this.getS_cardno()!=null)
						{
						CommandSyncAssociator associator = new CommandSyncAssociator();
						associator.setContinueorrollback(false);
						associator.setCcode(this.getS_cardno());
						associator.setMode(4);
						associator.setCurpaid(this.getYingshou());
						associator.setIcode(Integer.parseInt(store.getValue("icode")+""));
						list.add(associator);
						
				
				 		}
						//从新执行update，因为CommandSyncAssociator已经将busistatus update 为其他值
						
						CommandSyncsql commandsql2 = new CommandSyncsql();
							String sql = "update s_service_po set busistatus='524288',paymode="+paymode+" where icode ='"
							+ icode + "'";
						commandsql2.getV().add(sql);
						
						list.add(commandsql2);
						
						final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
						.create(com.base.myproject.client.tools.GreetingService.class);
						greetingService.SendCommandSync(list,
						this);
				
						
						//store.trySave(store.getCurcowindex());
						
						
						 
				 }
				 @Override
					public void onFailure(Throwable caught) {
					
					 MessageBox.alert("错误", "网络出现连接失败！请重新提交。", null);
					}

					@Override
					public void onSuccess(CommandSyncReturnObject result) {
						
						if(result.isB())
						{
							store.setValue("busistatus", "524288");
							store.setValue("s_cardno",this.getS_cardno());
							//去掉提交标识
							store._trySaveed(store.getCurcowindex());
							//store._commitChanges(store.getAt(store.getCurcowindex()));
							//s_service_po_g_store.commitChanges();
							store.getAt(store.getCurcowindex()).clearBusistatus();
							setEnableed(true);
							Info.display("", "提交成功");
							this.close();
						}
						else
						{
							MessageBox.alert("错误", result.getMessage(), null);
						}
					}
			 };
			 
			 	

			 pd.setYingshou(Paid.getValue().doubleValue());
			 pd.show();
			}
			
		
		
	}

}
